package org.argus.job.server.gateway.core.loadbalancer;

import java.util.List;

import org.argus.job.common.model.JobServerInstance;
import org.argus.job.server.gateway.core.cache.AppAssignCacheMaintainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 基于App名称服务实例选择器.
 * 基于App名称选择服务实例逻辑独立出来，便于已有网关和自己定制的reactorServiceInstanceLoadBalancer进行集成
 * @Author 刘文/Cliff Liu
 * @Date 2024/11/19
 */
@Component
@Slf4j
public class AppNameServiceInstanceSelector {

    @Autowired
    private AppAssignCacheMaintainer appAssignCacheMaintainer;

    /**
     * 根据App名称获取服务实例.
     * @param serviceInstances
     * @param appName
     * @return
     */
    public Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> serviceInstances, String appName, String appId) {
        JobServerInstance targetInstance = appAssignCacheMaintainer.getServerInstance(appName, appId);
        if (targetInstance != null) {
            for (ServiceInstance serviceInstance : serviceInstances) {
                if (targetInstance.getIp().equals(serviceInstance.getHost())
                    && serviceInstance.getPort() == targetInstance.getPort()) {
                    return new DefaultResponse(serviceInstance);
                }
            }
        }
        log.warn("No server available for app name : {}", appName);
        return new EmptyResponse();
    }
}
